//二维码扫描模态框
function showPrintModal() {
	//closeVideo:接收视频流对象序列；canvasImg:接收定时器
	var closeVideo, canvasImg;
	var video = $('#_printModal video')[0];
	var canvas = $('#_printModal canvas')[0];
	var context = canvas.getContext('2d');
	//页面切换关闭模态框
	$(document).on("visibilitychange", function() {
		var page = this.visibilityState;
		if(page == "hidden") {
			//          $('#_printModal').modal('hide');
		}
	});
	//getUserMedia兼容性处理
	var getUserMedia = (constraints, success, error) => {
		if(navigator.mediaDevices.getUserMedia) {
			//最新的标准API
			navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
		} else if(navigator.webkitGetUserMedia) {
			//webkit核心浏览器
			navigator.webkitGetUserMedia(constraints).then(success).catch(error);
		} else if(navigator.mozGetUserMedia) {
			//firfox浏览器
			navigator.mozGetUserMedia(constraints).then(success).catch(error);
		} else if(navigator.getUserMedia) {
			//旧版API
			navigator.getUserMedia(constraints).then(success).catch(error);
		}
	}
	var capture = () => {
		//canvas上生成video里的图像
		context.drawImage(video, 0, 0, 300, 300);
		//toDataURL会返回一个data-URI（base64）然后对此进行解析
		qrcode.decode(canvas.toDataURL('image/png'));
		//解析图片结果回调
		qrcode.callback = (e) => {
			//解析失败都会返回error decoding QR Code"
			if(e != "error decoding QR Code") { //二维码解析成功
				//停止访问摄像头
				closeVideo.stop();
				//停止定时器
				clearInterval(canvasImg);
				//清空canvas上的图片
				context.clearRect(0, 0, canvas.width, canvas.height);
				//显示二维码内容
				alert(e);
			}
		}
	}
	//调用用户媒体设备, 访问摄像头
	if(navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
		//所在浏览器支持getUserMedia就调用
		getUserMedia({                
			video: {
//				id:deviceInfoId,
				width: 500,
				height: 500,
				//user前置摄像头
				facingMode: {
					//exact: "environment",
                   exact: "user"
				},

			} //基础配置，MDN上还有其他的介绍
		}, (stream) => { //getUserMedia访问摄像头成功的回调
			//显示模态框
			$('#_printModal').modal("show");
			//video接收摄像头捕获的视频流
			video.srcObject = stream;
			//视频流在video标签中播放
			video.play();
			//使用closeVideo变量接收视频流对象序列，用来之后的关闭操作
			closeVideo = stream.getTracks()[0];
			//定时器：每隔0.5s执行capture方法，在canvas上生成图片进行解析
			canvasImg = setInterval(capture, 500);
		}, () => { //getUserMedia访问摄像头失败的回调
			alert("访问用户媒体设备失败,请添加相机权限");
		});
	} else { //浏览器不存在getUserMedia方法
		alert('不支持访问用户媒体');
	}
}

function gotDevices(deviceInfos) {
        for (let i = 0; i < deviceInfos.length; ++i) {
            if (deviceInfos[i].kind === 'videoinput') {
                carema.push(deviceInfos[i].deviceId)
              }
        }
        deviceInfoId = carema[1];
}

var deviceInfoId="", //摄像头ID
    num = 0, //摄像头数量
    carema = []; //摄像头ID数组
    //在页面加载完成后获得设备ID数组
window.onload = navigator.mediaDevices.enumerateDevices().then(gotDevices);